package com.huxiu.yd.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.yd.R;
import com.huxiu.yd.ReviewListActivity;
import com.huxiu.yd.SpareDetailActivity;
import com.huxiu.yd.UserProfileActivity;
import com.huxiu.yd.ViewImageActivity;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.SpareItem;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * This class contains all butterknife-injected Views & Layouts from layout file
 * 'spare_list_item.xml'
 * for easy to all layout elements.
 *
 * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers
 *         (http://github.com/avast)
 */
public class SpareItemViewHolder implements OnClickListener {

    @InjectView(R.id.container)
    View container;

    @InjectView(R.id.avatar)
    public AvatarView avatar;

    @InjectView(R.id.username)
    public TextView username;

    @InjectView(R.id.release_time)
    public TextView releaseTime;

    @InjectView(R.id.release_time2)
    public TextView releaseTime2;

    @InjectView(R.id.gallery)
    public RecyclerView gallery;

    @InjectView(R.id.description)
    public TextView description;

    @InjectView(R.id.price)
    public TextView price;

    @InjectView(R.id.favorite_count)
    public TextView favoriteCount;

    @InjectView(R.id.comment_count)
    public TextView commentCount;

    @InjectView(R.id.share)
    public TextView share;

    @InjectView(R.id.favorite_layout)
    FrameLayout favoriteLayout;

    @InjectView(R.id.comment_layout)
    FrameLayout commentLayout;

    @InjectView(R.id.share_layout)
    FrameLayout shareLayout;

    @InjectView(R.id.city)
    TextView city;

    @InjectView(R.id.publisher_info_layout)
    View publisherInfoLayout;

    @InjectView(R.id.right_divider)
    View rightDivider;

    @InjectView(R.id.more_layout)
    View moreLayout;

    private Activity mContext;

    private SpareItem mItem;

    LinearLayoutManager mLinearLayoutManager;

    private WeakReference<BaseAdapter> mAdapter;

    public void setAdapter(BaseAdapter adapter) {
        mAdapter = new WeakReference<>(adapter);
    }

    public SpareItemViewHolder(View view, Activity context) {
        ButterKnife.inject(this, view);
        mContext = context;
        username.setOnClickListener(this);
        favoriteLayout.setOnClickListener(this);
        commentLayout.setOnClickListener(this);
        shareLayout.setOnClickListener(this);
        container.setOnClickListener(this);
        mLinearLayoutManager = new LinearLayoutManager(context);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    }

    private boolean isMine = false;

    public void bindItem(SpareItem item, boolean isMine, boolean isAttention) {
        this.isMine = isMine;
        if (isMine) {
            publisherInfoLayout.setVisibility(View.GONE);
        }
        mItem = item;
        avatar.setUserInfo(item.user_id, item.avatar, item.name);
        username.setText(item.name);
        username.setCompoundDrawablesWithIntrinsicBounds(0, 0, item.getUserDrawable(), 0);
        gallery.setLayoutManager(mLinearLayoutManager);
        GalleryAdapter adapter = new GalleryAdapter();
        gallery.setAdapter(adapter);
        releaseTime.setText(Utils.getDateString(item.create_time));
        releaseTime2.setText(Utils.getDateString(item.create_time));
        releaseTime2.setVisibility(isMine || isAttention ? View.VISIBLE : View.INVISIBLE);
        rightDivider.setVisibility(isMine || isAttention ? View.VISIBLE : View.GONE);
        moreLayout.setVisibility(isMine ? View.VISIBLE : View.GONE);
        moreLayout.setOnClickListener(this);
        city.setText(item.city_name);
        description.setText(item.title);
        price.setText("￥" + item.price);
        commentCount.setText(Integer.toString(item.comment_num));
        favoriteCount.setText(Integer.toString(item.like_num));
        favoriteCount.setCompoundDrawablesWithIntrinsicBounds(
                item.liked() ? R.drawable.favorite_yes : R.drawable.favorite_no, 0, 0, 0);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.avatar:
            case R.id.username:
                intent = new Intent(mContext, UserProfileActivity.class);
                intent.putExtra(Constants.USER_ID_KEY, mItem.user_id);
                intent.putExtra("avatar", mItem.avatar);
                intent.putExtra("username", mItem.name);
                mContext.startActivity(intent);
                break;
            case R.id.container:
                intent = new Intent(mContext, SpareDetailActivity.class);
                intent.putExtra(Constants.DISCOVERY_ITEM_KEY, mItem.toString());
                mContext.startActivity(intent);
                break;
            case R.id.comment_layout:
                intent = new Intent(mContext, ReviewListActivity.class);
                intent.putExtra(Constants.SPARE_ID_KEY, mItem.user_goods_id);
                mContext.startActivity(intent);
                break;
            case R.id.share_layout:

                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(mItem.images[0] + "!" + Utils
                                .dip2px(107) + "x" + Utils.dip2px(60));
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(mContext, mItem.title, mItem.share_url, "goods",
                                mItem.images[0], mItem.description, bmp);
                    }
                }.execute();

                break;
            case R.id.favorite_layout:
                likeSpareItem(mItem, mAdapter, mContext);
                break;
            case R.id.more_layout:
                deleteItem();
                break;
            default:
                break;
        }
    }

    private void deleteItem() {
        new AlertDialog.Builder(mContext).setTitle(R.string.confirm_action).setItems(new String[]{"删除", "取消"}, new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
//                    case 0:
//                        Intent intent = new Intent(mContext, PublishSpareActivity.class);
//                        intent.putExtra("item", mItem.toString());
//                        mContext.startActivity(intent);
//                        break;
                    case 0:
                        doDelete();
                        break;
                    case 1:
                        break;
                }
            }
        }).show();
    }

    private void doDelete() {
        String url = NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "del_user_goods");
        params.put("user_goods_id", mItem.user_goods_id);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, true, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                Utils.showToast(R.string.delete_success);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    Utils.showToast(error.getMessage());
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    class GalleryViewHolder extends ViewHolder {

        ImageView imageView;

        View marginView;

        public GalleryViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.image);
            marginView = itemView.findViewById(R.id.space);
        }
    }

    class GalleryAdapter extends Adapter<GalleryViewHolder> {

        @Override
        public GalleryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mContext.getLayoutInflater()
                    .inflate(R.layout.spare_item_gallery_item_view, parent, false);
            return new GalleryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(GalleryViewHolder holder, final int position) {
            final String image = mItem.images[position];
            ImageLoader.getInstance()
                    .displayImage(image + "!" + Utils.dip2px(107) + "x" + Utils.dip2px(60),
                            holder.imageView, ImageUtils.getProductDisplayOption(R.drawable
                                    .default_product_image));
            holder.marginView
                    .setVisibility(position == mItem.images.length - 1 ? View.GONE : View.VISIBLE);
            holder.imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ViewImageActivity.class);
                    intent.putExtra("urls", mItem.images);
                    intent.putExtra("pos",position);
                    mContext.startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mItem.images.length;
        }
    }

    public static void likeSpareItem(final SpareItem item, final WeakReference<BaseAdapter>adapter, final Activity context) {
        if (Settings.isLoggedIn()) {
            String url = NetworkConstants.GOODS_URL;
            Map<String, String> params = new LinkedHashMap<>();
            params.put("act", "user_operate");
            params.put("user_goods_id", String.valueOf(item.user_goods_id));
            params.put("operate_type", "favorite");
            params.put("type", item.liked() ? "2" : "1");
            GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                    BaseResponse.class,

                    true, params, new Response.Listener<BaseResponse>() {
                @Override
                public void onResponse(BaseResponse response) {
                    if (response.isSuccess()) {
                        if (item.like_status == 1) {
                            item.like_num--;
                            item.like_status = 0;
                            Utils.showToast(R.string.cancel_success);
                        } else {
                            item.like_num++;
                            item.like_status = 1;
                            Utils.showToast(R.string.favorite_success);
                        }
                        if (adapter != null && adapter.get() != null) {
                            adapter.get().notifyDataSetChanged();
                        }
                        if (context != null && (context instanceof SpareDetailActivity)) {
                            SpareDetailActivity activity = (SpareDetailActivity)context;
                            activity.updateLikeView();
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Throwable t = error.getCause();
                    if (t instanceof ErrorResponseException) {
                        Utils.showToast(error.getMessage());
                    } else {
                        Utils.showToast(R.string.generic_failure);
                    }
                }
            });
            NetworkHelper.getInstance().addToRequestQueue(request);
//            NetworkHelper.getInstance().getRequestQueue().start();
        } else {
            Utils.askLogIn(context);
        }
    }
}
